package com.hkd.friend.service.exam.Impl;

import cn.hutool.core.collection.CollectionUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hkd.common.core.constants.Constants;
import com.hkd.common.core.domain.TableDataInfo;
import com.hkd.common.core.utils.ThreadLocalUtil;
import com.hkd.friend.domain.exam.dto.ExamQueryDTO;
import com.hkd.friend.domain.exam.vo.ExamRankVO;
import com.hkd.friend.domain.exam.vo.ExamVO;
import com.hkd.friend.domain.user.vo.UserVO;
import com.hkd.friend.manager.ExamCacheManager;
import com.hkd.friend.mapper.exam.ExamMapper;
import com.hkd.friend.service.exam.IExamService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.hkd.common.core.controller.BaseController.getTableDataInfo;

@Slf4j
@Service
public class ExamServiceImpl implements IExamService {
    @Autowired
    private ExamMapper examMapper;

    @Autowired
    private ExamCacheManager examCacheManager;

    @Override
    public TableDataInfo list(ExamQueryDTO examQueryDTO) {
        //分页查询
        PageHelper.startPage(examQueryDTO.getPageNum(), examQueryDTO.getPageSize());
        //查询数据
        List<ExamVO> examVOList = examMapper.selectExamList(examQueryDTO);

        return getTableDataInfo(examVOList);
    }

    @Override
    public TableDataInfo redisList(ExamQueryDTO examQueryDTO) {

        //1.判断是否有缓存数据
        Long total = examCacheManager.getListSize(examQueryDTO.getType(), null);
        List<ExamVO> examVOList;
        if (total == null || total <= 0) {
            //分页查询
            PageHelper.startPage(examQueryDTO.getPageNum(), examQueryDTO.getPageSize());
            //查询数据
            examVOList = examMapper.selectExamList(examQueryDTO);

            examCacheManager.refreshCache(examQueryDTO.getType(), null);
            total = new PageInfo<>(examVOList).getTotal();
        } else {
            //从redis当中获取  竞赛列表的数据
            examVOList = examCacheManager.getExamVOList(examQueryDTO, null);
            total = examCacheManager.getListSize(examQueryDTO.getType(), null);
        }

        if (CollectionUtil.isEmpty(examVOList)) {
            return TableDataInfo.empty();
        }
        assembleExamVOList(examVOList);//统计是否报名
        return TableDataInfo.success(examVOList, total);
    }
    private void assembleExamVOList(List<ExamVO> examVOList) {
        Long userId = ThreadLocalUtil.get(Constants.USER_ID, Long.class);
        List<Long> userExamIdList = examCacheManager.getAllUserExamList(userId);
        if (CollectionUtil.isEmpty(userExamIdList)) {
            return;
        }
        for (ExamVO examVO : examVOList) {
            if (userExamIdList.contains(examVO.getExamId())) {
                examVO.setEnter(true);
            }
        }
    }
}
